from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
import json
# Create your views here.

def index(request):
    print(request.path)
    print(request.method)
    print(request.META)
    print(request.GET)
    name = HttpResponse()
    name.content = "Alex"
    name.status_code = 300
    return name
    #return HttpResponse("hello world!!")

def index_1(request):
    '''
    其他数据类型的返回值方法练习
    :param request:
    :return:
    '''
    import json
    data = ["a","b","c"]
    data_1 = {"name":"aaa","age":77}
    # return HttpResponse(json.dumps(data))
    # return JsonResponse(data,safe=False)
    return JsonResponse(data_1)

def methodTrans(request):
    '''
    不同的请求传参和接收参数练习
    :param request:
    :return:
    '''
    from django.http import QueryDict
    if request.method == "GET":
        print("request get = ", request.GET)
        data = request.GET.copy()
        data["aa"] = "xxxx"
        print("data = ",data)
        print("request aa = ", request.GET.get("aa"))  # 获取单个值
        print("request cc = ", request.GET.getlist("cc"))  # 多个值

    elif request.method == "POST":
        print("request post =",request.POST)

    elif request.method == "DELETE":
        print("request delete = ",QueryDict(request.body))
    return HttpResponse("")

def login(request):
    '''
    用户登录练习
    :param request:
    :return:
    '''
    if request.method == "POST":
        username = request.POST.get("username")
        userpass = request.POST.get("userpass")
        if username == "admin" and userpass == "123456":
            msg = "登陆成功"
        else:
            msg = "登录失败"
    else:
        msg = "请求方法不被允许"
    return HttpResponse(msg)

from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
def loginView(request):
    '''
    用户登录，结合数据库
    :param request:
    :return:
    '''
    if request.method == "POST":
        username = request.POST.get("username")
        userpass = request.POST.get("userpass")
        user = authenticate(request, username=username, password=userpass)
        if user is not None:
            login(request, user)
            return HttpResponse("用户登录成功")
        else:
            return HttpResponse("用户登陆失败")
    return render(request,"login.html")